﻿using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Entities;
using QMERP.Domain.Enums;

namespace QMERP.Infrastructure.EFCore.Extensions
{
    public static class LeaveStockOrderExtension
    {
        /// <summary>
        /// 取出此业务单未取消的出库单总片数
        /// </summary>
        /// <param name="query"></param>
        /// <param name="orderType"></param>
        /// <param name="businessOrderId"></param>
        /// <returns></returns>
        public static async Task<int> GetLeaveStockQtyAsync(this IQueryable<LeaveStockOrder> query, string businessOrderType, long businessOrderId)
        {
            return await query.GetByBusinessOrderIdAsync(businessOrderType, businessOrderId).SelectMany(s => s.LeaveStockOrderDetails).SelectMany(s => s.LeaveStockOrderDetail_LensDetails).SumAsync(s => s.Qty);
        }
        /// <summary>
        /// 取出此业务单未取消的出库单总片数(不包含id的)
        /// </summary>
        /// <param name="query"></param>
        /// <param name="orderType"></param>
        /// <param name="businessOrderId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<int> GetLeaveStockQtyAsync(this IQueryable<LeaveStockOrder> query, string businessOrderType, long businessOrderId, long id)
        {
            return await query.GetByBusinessOrderIdAsync(businessOrderType, businessOrderId, id).SelectMany(s => s.LeaveStockOrderDetails).SelectMany(s => s.LeaveStockOrderDetail_LensDetails).SumAsync(s => s.Qty);
        }
        /// <summary>
        /// 取出此业务单未取消的出库单(不包含id的)
        /// </summary>
        /// <param name="query"></param>
        /// <param name="orderType"></param>
        /// <param name="businessOrderId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static IQueryable<LeaveStockOrder> GetByBusinessOrderIdAsync(this IQueryable<LeaveStockOrder> query, string businessOrderType, long businessOrderId, long id)
        {
            return query.GetByBusinessOrderIdAsync(businessOrderType, businessOrderId).Where(x => x.Id != id);
        }
        /// <summary>
        /// 取出此业务单未取消的出库单
        /// </summary>
        /// <param name="query"></param>
        /// <param name="orderType"></param>
        /// <param name="businessOrderId"></param>
        /// <returns></returns>
        public static IQueryable<LeaveStockOrder> GetByBusinessOrderIdAsync(this IQueryable<LeaveStockOrder> query, string businessOrderType, long businessOrderId)
        {
            return query.Include(x => x.LeaveStockOrderDetails).ThenInclude(x => x.LeaveStockOrderDetail_LensDetails)
                .Include(x => x.LeaveStockOrderDetails).ThenInclude(x => x.Warehouse)
                .Include(x => x.LeaveStockOrderDetails).ThenInclude(x => x.Lens).AsNoTracking().Where(x => x.BusinessOrderType == businessOrderType && x.BusinessOrderId == businessOrderId && x.Status != LeaveStockOrderStatusEnum.Canceled.ToString());
        }
    }
}